import frappe
from erpnext.stock.doctype.serial_and_batch_bundle import serial_and_batch_bundle
# 猴子补丁方法

original_create_serial_batch_no_ledgers=serial_and_batch_bundle.create_serial_batch_no_ledgers
original_update_serial_batch_no_ledgers=serial_and_batch_bundle.update_serial_batch_no_ledgers

def custom_create_serial_batch_no_ledgers(
	entries, child_row, parent_doc, warehouse=None, do_not_save=False
) -> object:
    # 自己添加
	# 自动添加批号
	batch_nos={frappe._dict(row).batch_no for row in entries if row.get("batch_no")}
	if batch_nos:
		batch_no_in=frappe.get_list('Batch',{'batch_id':['in',batch_nos],'item':child_row.item_code},'batch_id', pluck='batch_id')
		for batch_id in batch_nos:
			if batch_id not in batch_no_in:
				batch_doc=frappe.new_doc('Batch')
				batch_doc=batch_doc.update({
					'batch_id':batch_id,
					'item':child_row.item_code
					}).save()
	# 自动添加序列号
	serial_nos=[d.get("serial_no") for d in entries if d.get("serial_no")]
	if serial_nos:
		serial_no_in=frappe.get_list('Serial No',{'serial_no':['in',serial_nos],'item_code':child_row.item_code},'serial_no', pluck='serial_no')
		for serial_no in serial_nos:
			if serial_no not in serial_no_in:
				serial_doc=frappe.new_doc('Serial No')
				serial_doc=serial_doc.update({
					'serial_no':serial_no,
					'item_code':child_row.item_code
					}).save()
# 自己添加的
	return original_create_serial_batch_no_ledgers(entries, child_row, parent_doc, warehouse,do_not_save)

serial_and_batch_bundle.create_serial_batch_no_ledgers=custom_create_serial_batch_no_ledgers



def custom_update_serial_batch_no_ledgers(entries, child_row, parent_doc, warehouse=None) -> object:
	# 自己添加
	# 自动添加批号
	batch_nos=[d.get("batch_no") for d in entries if d.get("batch_no")]
	if batch_nos:
		batch_no_in=frappe.get_list('Batch',{'batch_id':['in',batch_nos],'item':child_row.item_code},'batch_id', pluck='batch_id')
		for batch_id in batch_nos:
			if batch_id not in batch_no_in:
				batch_doc=frappe.new_doc('Batch')
				batch_doc=batch_doc.update({
					'batch_id':batch_id,
					'item':child_row.item_code
					}).save()
# 自动添加序列号
	serial_nos=[frappe._dict(row).serial_no for row in entries if row.get("serial_no")]
	if serial_nos:
		serial_no_in=frappe.get_list('Serial No',{'serial_no':['in',serial_nos],'item_code':child_row.item_code},'serial_no', pluck='serial_no')
		for serial_no in serial_nos:
			if serial_no not in serial_no_in:
				serial_doc=frappe.new_doc('Serial No')
				serial_doc=serial_doc.update({
					'serial_no':serial_no,
					'item_code':child_row.item_code
					}).save()

   # 自己添加的
	return original_update_serial_batch_no_ledgers(entries, child_row, parent_doc, warehouse)

serial_and_batch_bundle.update_serial_batch_no_ledgers=custom_update_serial_batch_no_ledgers